package com.atguigu.gulimall.product.utils;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @description: 两个list进行比较， 获得交集和第二个相对于第一个list移除、新增的数据
* @author Yven
* @date 2022/7/14 17:13
*/
public class ListCompareHelper <T> {

    private final List<T> removedList;

    private final List<T> insertedList;

    private final Map<T,T> intersection;

    public static <T,K> ListCompareHelper<T> build(List<T> ver1, List<T> ver2
            , Function<? super T, ? extends K> keyMapper) {

        if(ver1 == null || ver2 == null){
            throw new RuntimeException("ver must not be null");
        }
        Map<Object ,T> ver1Map = ver1.stream().collect(Collectors.toMap(keyMapper, v -> v , (k1, k2) -> k2));
        Map<Object ,T> ver2Map = ver2.stream().collect(Collectors.toMap(keyMapper, v -> v , (k1, k2) -> k2));

        LinkedList<T> removedList = new LinkedList<T>();
        LinkedList<T> insertedList = new LinkedList<T>();
        LinkedHashMap<T,T> intersection = new LinkedHashMap<T,T>();

        ver1Map.forEach((k, v) -> {
            if(ver2Map.containsKey(k)) {
                intersection.put(v, ver2Map.get(k));
            } else {
                removedList.add(v);
            }
        });
        ver2Map.forEach((k, v) -> {
            if(!ver1Map.containsKey(k)) {
                insertedList.add(v);
            }
        });
        return new ListCompareHelper<T>(removedList,insertedList,intersection);

    }

    public static <T> ListCompareHelper<T> build(List<T> ver1 , List<T> ver2) {
        return build(ver1, ver2, k -> k);
    }

    public ListCompareHelper(List<T> removedList, List<T> insertedList, Map<T, T> intersection) {
        this.removedList = removedList;
        this.insertedList = insertedList;
        this.intersection = intersection;
    }

    public List<T> getRemovedList() {
        return removedList;
    }

    public List<T> getInsertedList() {
        return insertedList;
    }

    public Map<T, T> getIntersection() {
        return intersection;
    }

}
